<template>
  <div class="h-screen overflow-hidden">
    <div class="flex h-full">
      <div class="w-1/2 bg-gradient-to-br from-blue-600 to-blue-700 text-white p-12 flex flex-col justify-center items-center">
        <div class="max-w-md mx-auto">
          <div class="mb-12">
            <img :src="logoUrl" alt="Logo" class="w-32 h-32 rounded-full mx-auto object-cover" />
          </div>
          <h1 class="text-4xl font-bold mb-4 text-center">身份验证中心</h1>
          <p class="text-blue-100 text-lg mb-16 text-center">多重验证机制，保障系统安全</p>
          <div class="space-y-8">
            <div class="flex items-start space-x-4">
              <div class="w-12 h-12 bg-white/10 rounded-lg flex items-center justify-center flex-shrink-0">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>
              </div>
              <div>
                <h3 class="text-xl font-semibold mb-2">双重验证</h3>
                <p class="text-blue-100">结合多种验证方式，确保管理员身份真实可靠</p>
              </div>
            </div>
            <div class="flex items-start space-x-4">
              <div class="w-12 h-12 bg-white/10 rounded-lg flex items-center justify-center flex-shrink-0">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"/></svg>
              </div>
              <div>
                <h3 class="text-xl font-semibold mb-2">数据加密</h3>
                <p class="text-blue-100">所有验证数据均经过高强度加密处理</p>
              </div>
            </div>
            <div class="flex items-start space-x-4">
              <div class="w-12 h-12 bg-white/10 rounded-lg flex items-center justify-center flex-shrink-0">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
              </div>
              <div>
                <h3 class="text-xl font-semibold mb-2">操作审计</h3>
                <p class="text-blue-100">所有管理员操作均被记录，便于追溯和审计</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="w-1/2 bg-gray-50 p-12 overflow-y-auto">
        <div class="max-w-xl mx-auto">
          <div class="mb-8">
            <h2 class="text-3xl font-bold text-gray-900 mb-2">管理员身份验证</h2>
            <p class="text-gray-600">请完成以下验证步骤以继续操作</p>
          </div>
          <div class="flex items-center justify-between mb-12">
            <div class="flex flex-col items-center">
              <div :class="['step-circle', currentStep>=1 ? 'active' : 'inactive']">1</div>
              <span class="text-sm mt-2 font-medium" :class="currentStep>=1 ? 'text-gray-900' : 'text-gray-500'">选择验证方式</span>
            </div>
            <div class="flex-1 h-0.5 bg-gray-300 mx-4"></div>
            <div class="flex flex-col items-center">
              <div :class="['step-circle', currentStep>=2 ? 'active' : 'inactive']">2</div>
              <span class="text-sm mt-2" :class="currentStep>=2 ? 'text-gray-900' : 'text-gray-500'">进行身份验证</span>
            </div>
            <div class="flex-1 h-0.5 bg-gray-300 mx-4"></div>
            <div class="flex flex-col items-center">
              <div :class="['step-circle', currentStep>=3 ? 'active' : 'inactive']">3</div>
              <span class="text-sm mt-2" :class="currentStep>=3 ? 'text-gray-900' : 'text-gray-500'">验证成功</span>
            </div>
        </div>
        
          <div v-if="currentStep===1" class="mb-8">
            <h3 class="text-sm font-medium text-gray-700 mb-4">选择验证方式</h3>
            <div class="grid grid-cols-2 gap-4">
              <div :class="['verification-option border-2 rounded-lg p-4', selectedMethod==='sms' ? 'selected border-blue-600 bg-blue-50' : 'border-gray-200']" @click="selectedMethod='sms'; currentStep=2">
                <div class="flex items-start space-x-3">
                  <svg class="w-6 h-6 flex-shrink-0 mt-1" :class="selectedMethod==='sms' ? 'text-blue-600' : 'text-gray-400'" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"/></svg>
                  <div>
                    <h4 class="font-semibold text-gray-900">短信验证</h4>
                    <p class="text-sm text-gray-600">通过绑定手机接收验证码</p>
                  </div>
                </div>
              </div>
              <div :class="['verification-option border-2 rounded-lg p-4', selectedMethod==='account' ? 'selected border-blue-600 bg-blue-50' : 'border-gray-200']" @click="selectedMethod='account'; currentStep=2">
                <div class="flex items-start space-x-3">
                  <svg class="w-6 h-6 flex-shrink-0 mt-1" :class="selectedMethod==='account' ? 'text-blue-600' : 'text-gray-400'" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"/></svg>
                  <div>
                    <h4 class="font-semibold text-gray-900">账号验证</h4>
                    <p class="text-sm text-gray-600">通过输入密码验证</p>
                  </div>
                </div>
              </div>
            </div>
        </div>
        
          <div v-if="currentStep===2 && selectedMethod==='sms'" class="mb-6">
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700 mb-2">手机号</label>
              <input v-model="phone" type="tel" placeholder="请输入管理员手机号" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
            </div>
            <label class="block text-sm font-medium text-gray-700 mb-2">验证码</label>
            <div class="flex space-x-3">
              <div class="flex-1 relative">
                <svg class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>
                <input v-model="code" type="text" placeholder="请输入验证码" class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
              </div>
              <button class="px-6 py-3 bg-white border-2 border-blue-600 text-blue-600 rounded-lg font-medium hover:bg-blue-50 transition-colors whitespace-nowrap" @click="sendCode" :disabled="countdown>0">{{ countdown>0 ? countdown+'s 后重发' : '获取验证码' }}</button>
            </div>
            <div class="flex justify-between mt-6">
              <button class="px-4 py-2 text-gray-600 hover:text-gray-900" @click="currentStep=1">返回选择</button>
              <button class="px-6 py-3 bg-blue-600 text-white rounded-lg font-semibold hover:bg-blue-700 transition-colors" @click="completeVerify">完成验证</button>
            </div>
        </div>
        
          <!-- 账号验证（步骤二） -->
          <div v-if="currentStep===2 && selectedMethod==='account'" class="mb-6">
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700 mb-2">手机号</label>
              <input v-model="phone" type="tel" placeholder="请输入管理员手机号" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
            </div>
            <label class="block text-sm font-medium text-gray-700 mb-2">管理员密码</label>
            <div class="relative">
              <svg class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2v5a2 2 0 01-2 2H9a2 2 0 01-2-2V9a2 2 0 012-2h6zM9 12h6"/></svg>
              <input v-model="accountPassword" type="password" placeholder="请输入管理员密码" class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
            </div>
            <div class="flex justify-between mt-6">
              <button class="px-4 py-2 text-gray-600 hover:text-gray-900" @click="currentStep=1">返回选择</button>
              <button class="px-6 py-3 bg-blue-600 text-white rounded-lg font-semibold hover:bg-blue-700 transition-colors" @click="completeVerify">完成验证</button>
            </div>
          </div>

          <!-- 成功（步骤三） -->
          <div v-if="currentStep===3" class="mb-6">
            <div class="bg-green-50 border border-green-200 rounded-lg p-6 flex items-start gap-3">
              <svg class="w-6 h-6 text-green-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
              <div>
                <h4 class="text-lg font-semibold text-green-800 mb-1">身份验证成功</h4>
                <p class="text-green-700 text-sm">正在跳转到管理员控制台…</p>
              </div>
            </div>
            <div class="text-right mt-6">
              <button class="px-6 py-3 bg-blue-600 text-white rounded-lg font-semibold hover:bg-blue-700 transition-colors" @click="$router.push('/admin/dashboard')">立即进入</button>
            </div>
          </div>

          <div class="text-center text-sm text-gray-500">
            <p class="mb-1">无法完成验证? <a href="#" class="text-blue-600 hover:underline">联系超级管理员</a></p>
            <p>© 2025 快递代拿管理系统 版权所有 | <a href="#" class="hover:underline">安全政策</a> | <a href="#" class="hover:underline">隐私条款</a></p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import logo from '@/../头像.jpg'
export default {
  name: 'AdminLogin',
  data() {
    return {
      logoUrl: logo || '',
      selectedMethod: 'account',
      code: '',
      countdown: 0,
        phone: '',
      sentCode: '',
      accountPassword: '',
      currentStep: 1
    }
  },
  methods: {
    // 验证手机号格式（11位且以1开头）
    validatePhone(phone) {
      const phoneRegex = /^1\d{10}$/;
      return phoneRegex.test(phone);
    },
    
    async sendCode() {
      if (this.countdown > 0) return
      if (!this.phone) { alert('请先输入手机号'); return }
      if (!this.validatePhone(this.phone)) { alert('请输入正确的11位手机号码（以1开头）'); return }

      try {
        const res = await fetch('/api/auth/send-sms', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ phone: this.phone })
        })
        const result = await res.json().catch(() => ({}))

        if (res.ok && result.success) {
          if (result.data && result.data.smsCode) {
            alert(`开发环境提示：短信验证码为 ${result.data.smsCode}`)
          } else {
            alert('验证码已发送，请查收')
          }

          this.countdown = 60
          const timer = setInterval(() => {
            this.countdown--
            if (this.countdown <= 0) clearInterval(timer)
          }, 1000)
        } else {
          alert(result.message || '发送验证码失败')
        }
      } catch (e) {
        console.error('发送验证码错误:', e)
        alert('发送验证码失败，请重试')
      }
    },
    
    async completeVerify() {
      if (this.selectedMethod === 'sms') {
        if (!this.phone) { alert('请输入手机号'); return }
        if (!this.validatePhone(this.phone)) { alert('请输入正确的11位手机号码（以1开头）'); return }
        if (!this.code) { alert('请输入验证码'); return }

        try {
          const res = await fetch('/api/auth/login-with-sms', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              phone: this.phone,
              smsCode: this.code,
              isAdminLogin: true
            })
          })
          const result = await res.json().catch(() => ({}))

          if (res.ok && result.success && result.data && result.data.role === 'admin') {
            localStorage.setItem('adminToken', result.data.accessToken || 'verified')
            localStorage.setItem('adminInfo', JSON.stringify({
              id: result.data.userId,
              phone: this.phone,
              role: 'admin',
              verifiedAt: Date.now(),
              method: 'sms'
            }))
            this.currentStep = 3
            setTimeout(() => this.$router.push('/admin/dashboard'), 800)
          } else {
            alert(result.message || '管理员身份验证失败（请确认该手机号为管理员账号）')
          }
        } catch (e) {
          console.error('管理员验证码登录失败:', e)
          alert('网络错误，请稍后重试')
        }
        return
      }

      if (this.selectedMethod === 'account') {
        if (!this.phone) { alert('请输入手机号'); return }
        if (!this.validatePhone(this.phone)) { alert('请输入正确的11位手机号码（以1开头）'); return }
        if (!this.accountPassword) { alert('请输入密码'); return }
        try {
          // 调用管理员专用登录接口，而不是通用登录接口
          const res = await fetch('/api/admin/login', {
            method: 'POST', 
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
              phone: this.phone, 
              password: this.accountPassword 
            })
          })
          const result = await res.json().catch(() => ({}))
          
          if (res.ok && result.success) {
            localStorage.setItem('adminToken', result.data.token || 'verified')
            localStorage.setItem('adminInfo', JSON.stringify(result.data.admin || { 
              role: 'admin', 
              verifiedAt: Date.now(), 
              method: 'account' 
            }))
            this.currentStep = 3
            setTimeout(() => this.$router.push('/admin/dashboard'), 800)
          } else {
            alert(result.message || '管理员身份验证失败')
          }
        } catch (e) {
          alert('网络错误，请稍后重试')
        }
      }
    }
  }
}
</script>

<style scoped>
.verification-option { transition: all 0.3s ease; cursor: pointer; }
.verification-option:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
.verification-option.selected { border-color: #2563eb; background-color: #eff6ff; }
.step-circle { width: 40px; height: 40px; border-radius: 50%; display:flex; align-items:center; justify-content:center; font-weight:600; transition: all 0.3s ease; }
.step-circle.active { background-color: #2563eb; color: #fff; }
.step-circle.inactive { background-color: #e5e7eb; color: #9ca3af; }
</style>